# @Time : 2024/11/7 22:20
# @Author : Fioman 
# @Phone : 13149920693
"""
如何构建一摞有序的扑克牌,按照黑桃红桃梅花方片的方式排列.
"""
import random
from collections import namedtuple

Card = namedtuple("Card", ["rank", "suit"])
getitemIsPrint = False


class Poker:
    ranks = [str(i) for i in range(2, 11)] + list("JQKA")
    suits = ["黑桃", "红桃", "梅花", "方片"]

    def __init__(self):
        self._cards = ([Card(rank, suit) for suit in Poker.suits for rank in Poker.ranks] +
                       [Card("小鬼", ""), Card("大鬼", "")])
        print(self._cards)

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, item):
        global getitemIsPrint
        if getitemIsPrint:
            print("in __getitem__() 调用")
        res = self._cards[item]
        # if isinstance(res, list):
        #     # 如果返回的是一个列表就将里面的内容逐个地转换成为字符串
        #     res = [card.suit + card.rank for card in res]
        # else:
        #     res = self._cards[item].suit + self._cards[item].rank
        return res

    def __str__(self):
        return str([card.suit + card.rank for card in self._cards])

    @staticmethod
    def spades_high(card):
        if card.rank == "大鬼":
            rankValue = 54
        elif card.rank == "小鬼":
            rankValue = 53
        else:
            rankValue = Poker.ranks.index(card.rank)

        suitsValue = {"黑桃": 3, "红桃": 2, "方片": 1, "梅花": 0}
        return rankValue * 4 + suitsValue.get(card.suit, 0)


if __name__ == '__main__':
    poker = Poker()
    print("扑克牌总个数: {}".format(len(poker)))  # 调用__len__方法
    print("打印扑克: {}".format(poker))
    # 1. 获取第一张和最后一张以及中间的一张
    first = poker[0]
    last = poker[-1]
    middle = poker[len(poker) // 2]
    print(f"First: {first}, Last: {last}, Middle: {middle}")
    # 随机的获取一张牌,可以使用random中的choice()方法,choice()方法就是随机的从序列中获取一项
    cardRandom = random.choice(poker)
    print(f"randomCard: {cardRandom}")
    # 2. 反向迭代
    for card in reversed(poker):
        print(card)

    getitemIsPrint = True
    # 支持in计算符号,使用in计算符号的时候,如果没有__contains__方法,也会调用for循环,进而调用__getitem__
    if cardRandom in poker:
        print("True")
    else:
        print("False")

    for card in sorted(poker, key=Poker.spades_high):
        print(card)
